package com.dz.customer.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dz.customer.entity.Customer;
import com.dz.customer.mapper.CustomerDao;
import com.dz.customer.service.CustomerService;

/**
 * <p>
 * 客户基本表 服务实现类
 * </p>
 *
 * @author star
 * @since 2017-06-27
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, Customer> implements CustomerService {

	public Customer selectByOpenId(String openId) {
		Wrapper<Customer> cWrapper = new EntityWrapper<Customer>();
		cWrapper.eq("fopenId", openId);
		List<Customer> customers = baseMapper.selectList(cWrapper);
		if (customers.size() > 0) {
			return customers.get(0);
		}
		return null;
	}

	public Long selectByPhone(String num) {
		Wrapper<Customer> cWrapper = new EntityWrapper<Customer>();
		cWrapper.eq("fmobile", num);
		List<Customer> customers = baseMapper.selectList(cWrapper);
		if (customers.size() > 0) {
			Customer customer = customers.get(0);
			return customer.getId();
		}
		return null;
	}

	@Override
	public Customer saveWxUserInfo(Customer customer) {
		Assert.notNull(customer.getOpenId(), "openId 不能为空");
		Customer rawData = selectByOpenId(customer.getOpenId());
		if (rawData == null) {
			insert(customer);
			return customer;
		} else {
			BeanUtils.copyProperties(customer, rawData, "id", "createDate", "createBy");
			rawData.setUpdateBy("wx");
			rawData.setUpdateDate(new Date());
			updateById(rawData);
			return rawData;
		}
	}
}
